package com.xh.bussiness.teachbook.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xh.bussiness.exam.bean.request.UserErrorQuestionSaveRequest;
import com.xh.bussiness.exam.constant.UserErrorQuestionConstant;
import com.xh.bussiness.exam.model.UserErrorQuestion;
import com.xh.bussiness.exam.service.IUserErrorQuestionService;
import com.xh.bussiness.system.model.Student;
import com.xh.bussiness.system.service.IStudentService;
import com.xh.bussiness.teachbook.bean.dto.ErrorQuestionResultDto;
import com.xh.bussiness.teachbook.bean.dto.QuestionResultDto;
import com.xh.bussiness.teachbook.bean.dto.TeachingBookReportDto;
import com.xh.bussiness.teachbook.bean.request.SubmitStudentResultRequest;
import com.xh.bussiness.teachbook.dao.TeachingBookStudentResultMapper;
import com.xh.bussiness.teachbook.model.*;
import com.xh.bussiness.teachbook.service.*;
import com.xh.bussiness.tiku.bean.dto.QuestionDto;
import com.xh.bussiness.tiku.service.IQuestionService;
import com.xh.core.exception.XhException;
import com.xh.core.service.impl.BaseServiceImpl;
import com.xh.core.util.MathUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.aspose.slides.ms.core.pbdb106a0.b.*;

/**
 * <p>
 *
 * </p>
 *
 * @author Pitt zhang
 * @since 2019/9/11
 */
@Service
public class TeachingBookStudentResultServiceImpl extends BaseServiceImpl<TeachingBookStudentResultMapper, TeachingBookStudentResult> implements ITeachingBookStudentResultService {

    @Autowired
    private ITeachingBookPracticeService teachingBookPracticeService;
    @Autowired
    private ITeachingBookStudentQuestionResultService teachingBookStudentQuestionResultService;
    @Autowired
    private ITeachingBookModuleDetailService teachingBookModuleDetailService;
    @Autowired
    private IQuestionService questionService;
    @Autowired
    private ITeachingBookService teachingBookService;
    @Autowired
    private IUserErrorQuestionService userErrorQuestionService;
    @Autowired
    private IStudentService studentService;

    @Override
    public String submitTeachingBookStudentResult(List<SubmitStudentResultRequest> studentResultRequests) {
        if (CollectionUtils.isEmpty(studentResultRequests)) {
            return "作答结果不能为空";
        }
        TeachingBookPractice practice = teachingBookPracticeService.getById(studentResultRequests.get(0).getTeachingBookPracticeId());
        if (practice == null) {
            return "备课练习不存在";
        }
        List<TeachingBookStudentQuestionResult> studentQuestionResults = new ArrayList<>();
        for (SubmitStudentResultRequest studentResultRequest : studentResultRequests) {
            QueryWrapper<TeachingBookStudentResult> studentResultQueryWrapper = new QueryWrapper<>();
            studentResultQueryWrapper.eq("student_id", studentResultRequest.getStudentId());
            studentResultQueryWrapper.eq("teaching_book_id", studentResultRequest.getTeachingBookId());
            studentResultQueryWrapper.eq("teaching_book_practice_id", studentResultRequest.getTeachingBookPracticeId());

            TeachingBookStudentResult teachingBookStudentResult = this.selectOne(studentResultQueryWrapper, TeachingBookStudentResult.class);
            if (teachingBookStudentResult == null) {
                //学生成绩录入
                teachingBookStudentResult = new TeachingBookStudentResult();
                teachingBookStudentResult.setTeachingBookId(studentResultRequest.getTeachingBookId());
                teachingBookStudentResult.setTeachingBookPracticeId(studentResultRequest.getTeachingBookPracticeId());
                teachingBookStudentResult.setStudentId(studentResultRequest.getStudentId());
                teachingBookStudentResult.setStudentName(studentResultRequest.getStudentName());
                //错题数
                int errorQuestionCount = CollectionUtils.isEmpty(studentResultRequest.getErrorQuestionResultDtos()) ? 0 : studentResultRequest.getErrorQuestionResultDtos().size();
                //例题数
                int questionCount = CollectionUtils.isEmpty(studentResultRequest.getQuestionResultDtos()) ? 0 : studentResultRequest.getQuestionResultDtos().size();
                //练习作业例题数
                int practiceQuestionCount = CollectionUtils.isEmpty(studentResultRequest.getPracticeQuestionResultDtos()) ? 0 : studentResultRequest.getPracticeQuestionResultDtos().size();
             /*   teachingBookStudentResult.setErrorQuestionCount(errorQuestionCount);
                teachingBookStudentResult.setQuestionCount(questionCount);
                teachingBookStudentResult.setPracticeQuestionCount(practiceQuestionCount);
                teachingBookStudentResult.setTotalScore(practice.getTotalScore());*/
                this.insert(teachingBookStudentResult);
            } else {
                teachingBookStudentQuestionResultService.deleteByStudentResultId(teachingBookStudentResult.getId(), Arrays.asList(1, 2));
            }

            List<ErrorQuestionResultDto> errorQuestionResultDtos = studentResultRequest.getErrorQuestionResultDtos();
            if (!CollectionUtils.isEmpty(errorQuestionResultDtos)) {
                //学生错题作答结果
                for (ErrorQuestionResultDto errorQuestionResultDto : errorQuestionResultDtos) {
                    TeachingBookStudentQuestionResult errorQuestionResult = new TeachingBookStudentQuestionResult();
                    errorQuestionResult.setStudentResultId(teachingBookStudentResult.getId());
                    errorQuestionResult.setQuestionId(errorQuestionResultDto.getQuestionId());
                    //试题来源：1.错题，2.练习题,3.课后作业练习题
                    errorQuestionResult.setQuestionSourceType(1);
                 //   errorQuestionResult.setErrorQuestionStartNum(errorQuestionResultDto.getStartNum());
                    errorQuestionResult.setCorrect(errorQuestionResultDto.getCorrect());
                    studentQuestionResults.add(errorQuestionResult);
                }
            }
            List<QuestionResultDto> questionResultDtos = studentResultRequest.getQuestionResultDtos();
            if (!CollectionUtils.isEmpty(questionResultDtos)) {
                //备课试题
                for (QuestionResultDto questionResultDto : questionResultDtos) {
                    TeachingBookStudentQuestionResult questionResult = new TeachingBookStudentQuestionResult();
                    questionResult.setStudentResultId(teachingBookStudentResult.getId());
                    questionResult.setQuestionId(questionResultDto.getQuestionId());
                    //试题来源：1.错题，2.练习题,3.课后作业练习题
                    questionResult.setQuestionSourceType(2);
                    questionResult.setCorrect(questionResultDto.getCorrect());
                    studentQuestionResults.add(questionResult);
                }
            }
            List<QuestionResultDto> practiceQuestionResultDtos = studentResultRequest.getPracticeQuestionResultDtos();
            if (!CollectionUtils.isEmpty(practiceQuestionResultDtos)) {
                //作业试题
                Double score = 0.0;
                for (QuestionResultDto practiceQuestionResultDto : practiceQuestionResultDtos) {
                    TeachingBookStudentQuestionResult practiceQuestionResult = new TeachingBookStudentQuestionResult();
                    practiceQuestionResult.setStudentResultId(teachingBookStudentResult.getId());
                    practiceQuestionResult.setQuestionId(practiceQuestionResult.getQuestionId());
                    practiceQuestionResult.setCorrect(practiceQuestionResultDto.getCorrect());
                    //累加分数
                    if (practiceQuestionResultDto.getCorrect().equals(1)) {
                        score += practiceQuestionResultDto.getScore();
                        practiceQuestionResult.setScore(practiceQuestionResultDto.getScore());
                    } else {
                        practiceQuestionResult.setScore(0);
                    }
                    //试题来源：1.错题，2.练习题,3.课后作业练习题
                    practiceQuestionResult.setQuestionSourceType(3);
                    studentQuestionResults.add(practiceQuestionResult);
                }
           //     teachingBookStudentResult.setScore(score);
                //更新保存状态
                teachingBookStudentResult.setStatus(studentResultRequest.getStatus());
                this.update(teachingBookStudentResult);
            }
        }
        if (!CollectionUtils.isEmpty(studentQuestionResults)) {
            teachingBookStudentQuestionResultService.batchInsert(studentQuestionResults);
        }
        return null;
    }

    @Override
    public TeachingBookReportDto queryTeachingBookStudentReport(String studentId, String teachingBookId) {
        TeachingBookReportDto dto = new TeachingBookReportDto();

        QueryWrapper<TeachingBookStudentResult> studentResultQueryWrapper = new QueryWrapper();
        studentResultQueryWrapper.eq("teaching_book_id", teachingBookId);
        studentResultQueryWrapper.eq("student_id", studentId);
        TeachingBookStudentResult studentResult = this.selectOne(studentResultQueryWrapper, TeachingBookStudentResult.class);
        if (studentResult == null) {
            return dto;
        }
        //学生试题作答结果
        QueryWrapper<TeachingBookStudentQuestionResult> studentQuestionResultQueryWrapper = new QueryWrapper<>();
        studentQuestionResultQueryWrapper.eq("student_result_id", studentResult.getId());
        List<TeachingBookStudentQuestionResult> studentQuestionResults = teachingBookStudentQuestionResultService.selectList(studentQuestionResultQueryWrapper, TeachingBookStudentQuestionResult.class);
        if (CollectionUtils.isEmpty(studentQuestionResults)) {
            return dto;
        }

        //获取当前备课上次备课课后作业
        Map<String, Object> practiceMap = null;//teachingBookPracticeService.queryPreTeachingBookPracticeDetail(null,teachingBookId);
        TeachingBook teachingBook = teachingBookService.getById(teachingBookId);


        dto.setTitle(teachingBook.getName());
        dto.setStudentName(studentResult.getStudentName());
      /*  dto.setQuestionCount(studentResult.getQuestionCount());
        dto.setErrorQuestionCount(studentResult.getErrorQuestionCount());*/
        //错题掌握程度： SUM(每个错题获取分数)/错题数
        Double masterRate = 0.0;
        //备课试题正确率
        Double questionRightRate = 0.0;
        //课后作业题数
        Integer practiceQuestionCount = 0;
        //作业总分
        Integer practiceTotalScore = 0;
        //作业得分
        Integer practiceScore = 0;
        //试题来源：1.错题，2.练习题,3.课后作业练习题
        Map<Integer, List<TeachingBookStudentQuestionResult>> questionMap = studentQuestionResults.stream().collect(Collectors.groupingBy(item -> item.getQuestionSourceType()));

        //学生错题作答结果
        List<TeachingBookStudentQuestionResult> studentErrorQuestionResults = questionMap.get(1);
        if (!CollectionUtils.isEmpty(studentErrorQuestionResults)) {
            //学生错题累积获得总星数
        //    Integer studentTotalStartNum = studentErrorQuestionResults.stream().filter(item -> item.getCorrect().equals(1)).collect(Collectors.summingInt(item -> item.getErrorQuestionStartNum()));
            //错题掌握程度 SUM(每个错题获取分数)/错题数
       //     masterRate = MathUtils.divTwoNumberRoundHalfUp(studentTotalStartNum, studentErrorQuestionResults.size(), MathUtils.DEFAULT_SCALE);
        }
        //备课试题正确率
        List<TeachingBookStudentQuestionResult> studentTeachingBookQuestionResults = questionMap.get(2);
        if (!CollectionUtils.isEmpty(studentTeachingBookQuestionResults)) {
            Long rightCount = studentTeachingBookQuestionResults.stream().filter(item -> item.getCorrect().equals(1)).count();
            questionRightRate = MathUtils.getNumberRate(MathUtils.divTwoNumberRoundHalfUp(rightCount, studentTeachingBookQuestionResults.size(), MathUtils.DEFAULT_SCALE), MathUtils.DEFAULT_SCALE);
        }
        //作业得分
        List<TeachingBookStudentQuestionResult> studentPracticeQuestionResults = questionMap.get(3);
        if (!CollectionUtils.isEmpty(studentPracticeQuestionResults)) {
            practiceScore = studentPracticeQuestionResults.stream().filter(item -> item.getCorrect().equals(1)).collect(Collectors.summingInt(item -> item.getScore()));
        }
        //作业总分数
        if (practiceMap.containsKey("teachingBookPractice") && practiceMap.get("teachingBookPractice") != null) {
            TeachingBookPractice teachingBookPractice = (TeachingBookPractice) practiceMap.get("teachingBookPractice");
            practiceTotalScore = teachingBookPractice.getTotalScore();
        }
        //作业总题数
        if (practiceMap.containsKey("questions") && practiceMap.get("questions") != null) {
            List<TeachingBookPracticeContent> teachingBookPracticeContents = (List<TeachingBookPracticeContent>) practiceMap.get("questions");
            if (!CollectionUtils.isEmpty(teachingBookPracticeContents)) {
                practiceQuestionCount = teachingBookPracticeContents.size();
            }
        }
        dto.setPracticeTotalScore(practiceTotalScore);
        dto.setPracticeScore(practiceScore);
        dto.setPracticeQuestionCount(practiceQuestionCount);
        dto.setQuestionRightRate(questionRightRate);
        dto.setMasterRate(masterRate);

        //做错的试题集合
        List<QuestionDto> errorQuestionDtos = new ArrayList<>();
        List<String> errorQuestionIds = studentQuestionResults.stream().filter(item -> item.equals(0)).map(item -> item.getQuestionId()).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(errorQuestionIds)) {
            for (String errorQuestionId : errorQuestionIds) {
                QuestionDto question = questionService.getQuestion(errorQuestionId, null);
                errorQuestionDtos.add(question);
            }
        }
        dto.setErrorQuestionDto(errorQuestionDtos);

        return dto;
    }

    @Override
    public void submitNowTeachingBookStudentResult(SubmitStudentResultRequest submitStudentResultRequest) {
        QueryWrapper<TeachingBookStudentResult> studentResultQueryWrapper = new QueryWrapper<>();
        studentResultQueryWrapper.eq("student_id", submitStudentResultRequest.getStudentId());
        studentResultQueryWrapper.eq("teaching_book_id", submitStudentResultRequest.getTeachingBookId());

        TeachingBookStudentResult teachingBookStudentResult = this.selectOne(studentResultQueryWrapper, TeachingBookStudentResult.class);
        if (teachingBookStudentResult == null) {
            //学生成绩录入
            teachingBookStudentResult = new TeachingBookStudentResult();
            teachingBookStudentResult.setTeachingBookId(submitStudentResultRequest.getTeachingBookId());
            teachingBookStudentResult.setStudentId(submitStudentResultRequest.getStudentId());
            teachingBookStudentResult.setStudentName(submitStudentResultRequest.getStudentName());
            teachingBookStudentResult.setStatus(submitStudentResultRequest.getStatus());

            this.insert(teachingBookStudentResult);
        } else {
            teachingBookStudentResult.setStatus(submitStudentResultRequest.getStatus());
            this.update(teachingBookStudentResult);

            teachingBookStudentQuestionResultService.deleteByStudentResultId(teachingBookStudentResult.getId(), Arrays.asList(1, 2));
        }
        //处理学生错题
        Student student = studentService.addStudentByLwStudentId(submitStudentResultRequest.getStudentId());
        if (student == null) {
            throw new XhException("学生不存在！");
        }
        List<ErrorQuestionResultDto> errorQuestionResultDtos = submitStudentResultRequest.getErrorQuestionResultDtos();
        if (!CollectionUtils.isEmpty(errorQuestionResultDtos)) {
            for (ErrorQuestionResultDto item : errorQuestionResultDtos) {
                QuestionDto question = questionService.getQuestion(item.getQuestionId(), null);
                if (question == null) {
                    continue;
                }
                TeachingBookStudentQuestionResult questionResult = new TeachingBookStudentQuestionResult();
                questionResult.setQuestionId(item.getQuestionId());
                questionResult.setCorrect(item.getCorrect());
                questionResult.setStudentResultId(teachingBookStudentResult.getId());
                //来源错题
                questionResult.setQuestionSourceType(1);
                //保存作答试题
                teachingBookStudentQuestionResultService.insert(questionResult);
                //学生回答错误则添加到错题本
                if (!item.getCorrect().equals(0)) {
                    continue;
                }
                saveToUserErrorQuestion(student, question, "备课错题回顾");
            }
        }
        //课堂练习题处理
        List<QuestionResultDto> practiceQuestionResultDtos = submitStudentResultRequest.getQuestionResultDtos();
        if (!CollectionUtils.isEmpty(practiceQuestionResultDtos)) {
            for (QuestionResultDto practice : practiceQuestionResultDtos) {
                QuestionDto question = questionService.getQuestion(practice.getQuestionId(), null);
                if (question == null) {
                    continue;
                }
                TeachingBookStudentQuestionResult questionResult = new TeachingBookStudentQuestionResult();
                questionResult.setQuestionId(practice.getQuestionId());
                questionResult.setCorrect(practice.getCorrect());
                questionResult.setStudentResultId(teachingBookStudentResult.getId());
                //来源错题
                questionResult.setQuestionSourceType(2);
                //保存作答试题
                teachingBookStudentQuestionResultService.insert(questionResult);
                //学生回答错误则添加到错题本
                if (practice.getCorrect().equals(0)) {
                    saveToUserErrorQuestion(student, question, "课堂练习题");
                }
            }
        }
    }

    /**
     * 备课回答错误的试题保存到错题本
     * @param student
     * @param questionDto
     * @param questionSource
     */
    private void saveToUserErrorQuestion(Student student,QuestionDto questionDto,String questionSource) {
        QuestionDto question = questionService.getQuestion(questionDto.getId(), null);
        if (question == null) {
            return;
        }
        //保存或更新学生错题
        UserErrorQuestionSaveRequest userErrorQuestionSaveRequest = new UserErrorQuestionSaveRequest();
        userErrorQuestionSaveRequest.setStudentId(student.getLwStudentId());
        userErrorQuestionSaveRequest.setUserId(student.getUserId());
        userErrorQuestionSaveRequest.setQuestionVersion(1);
        userErrorQuestionSaveRequest.setQuestionId(questionDto.getId());
        userErrorQuestionSaveRequest.setSubjectId(question.getSubjectId());
        userErrorQuestionSaveRequest.setSourceType(UserErrorQuestionConstant.SOURCETYPE.TEACHER_MADE);
        userErrorQuestionSaveRequest.setQuestionSource(questionSource);
         userErrorQuestionService.addUserErrorQuestion(userErrorQuestionSaveRequest);
    }

    @Override
    public void submitPreTeachingBookPracticeStudentResult(SubmitStudentResultRequest submitStudentResultRequest) {
        TeachingBookPractice practice = teachingBookPracticeService.getById(submitStudentResultRequest.getTeachingBookPracticeId());
        if (practice == null) {
            throw new XhException("备课练习不存在");
        }
        QueryWrapper<TeachingBookStudentResult> studentResultQueryWrapper = new QueryWrapper<>();
        studentResultQueryWrapper.eq("student_id", submitStudentResultRequest.getStudentId());
        studentResultQueryWrapper.eq("teaching_book_id", submitStudentResultRequest.getTeachingBookId());

        TeachingBookStudentResult teachingBookStudentResult = this.selectOne(studentResultQueryWrapper, TeachingBookStudentResult.class);
        if (teachingBookStudentResult == null) {
            //学生成绩录入
            teachingBookStudentResult = new TeachingBookStudentResult();
            teachingBookStudentResult.setTeachingBookId(submitStudentResultRequest.getTeachingBookId());
            teachingBookStudentResult.setStudentId(submitStudentResultRequest.getStudentId());
            teachingBookStudentResult.setStudentName(submitStudentResultRequest.getStudentName());
            teachingBookStudentResult.setStatus(0);

            this.insert(teachingBookStudentResult);
        }
        List<QuestionResultDto> practiceQuestionResultDtos = submitStudentResultRequest.getPracticeQuestionResultDtos();
        List<TeachingBookStudentQuestionResult> studentQuestionResults = new ArrayList<>();
        if (!CollectionUtils.isEmpty(practiceQuestionResultDtos)) {
            teachingBookStudentQuestionResultService.deleteByStudentResultId(teachingBookStudentResult.getId(), Arrays.asList(2));
            //作业试题
            Double score = 0.0;
            for (QuestionResultDto practiceQuestionResultDto : practiceQuestionResultDtos) {
                TeachingBookStudentQuestionResult practiceQuestionResult = new TeachingBookStudentQuestionResult();
                practiceQuestionResult.setStudentResultId(teachingBookStudentResult.getId());
                practiceQuestionResult.setQuestionId(practiceQuestionResultDto.getQuestionId());
                practiceQuestionResult.setCorrect(practiceQuestionResultDto.getCorrect());
                //试题来源：1.错题，2.练习题,3.课后作业练习题
                practiceQuestionResult.setQuestionSourceType(3);
                studentQuestionResults.add(practiceQuestionResult);
            }
         //   teachingBookStudentResult.setScore(score);
            //更新保存状态
            teachingBookStudentResult.setStatus(1);
       /*     teachingBookStudentResult.setPracticeQuestionCount(studentQuestionResults.size());
            teachingBookStudentResult.setScore(score);
            teachingBookStudentResult.setTotalScore(practice.getTotalScore());*/
            this.update(teachingBookStudentResult);
        }
        if (!CollectionUtils.isEmpty(studentQuestionResults)) {
            teachingBookStudentQuestionResultService.batchInsert(studentQuestionResults);
        }
    }

    @Override
    public TeachingBookStudentResult queryByIdStudentAndTeachingBookId(String studentId, String teachingBookId) {
        QueryWrapper<TeachingBookStudentResult> qw = new QueryWrapper<>();
        qw.eq("teaching_book_id", teachingBookId);
        qw.eq("student_id", studentId);
        List<TeachingBookStudentResult> teachingBookStudentResults = this.dao.selectList(qw);
        if (!CollectionUtils.isEmpty(teachingBookStudentResults)) {
            return teachingBookStudentResults.get(0);
        }
        return null;
    }
}
